<template>
  <div class="cycle-scheduling">
    <div class="header">
      <div class="title-and-button">
        <h2>周期排班</h2>
        <el-button type="danger" @click="goToSchedule">
          去排班
        </el-button>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd">
          <el-icon>
            <Plus />
          </el-icon>新增周期排班
        </el-button>
        <el-input v-model="searchQuery" placeholder="请输入排班名称" clearable style="width: 240px; margin-left: 12px">
          <template #prefix>
            <el-icon>
              <Search />
            </el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <el-table :data="filteredSettings" style="width: 100%" row-key="settingId" v-loading="loading"
      :cell-style="{ padding: '8px 0' }">
      <el-table-column prop="settingName" label="周期名称" width="180" />
      <el-table-column prop="periodicContent" label="周期内容">
        <template #default="{ row }">
          <div class="rule-content">
            <el-tooltip effect="light" placement="top" popper-class="rule-tooltip">
              <template #content>
                <div class="tooltip-content">
                  <div>周期天数：{{ getCycleDays(row.periodicContent) }}</div>
                  <div v-for="(day, index) in parseContent(row.periodicContent)" :key="index">
                    第{{ index + 1 }}天：{{ formatDayContent(day) }}
                  </div>
                  <div v-if="parseContent(row.periodicContent).length === 0">
                    暂无排班详情
                  </div>
                </div>
              </template>
              <div class="content-text">
                <div>周期天数：{{ getCycleDays(row.periodicContent) }}</div>
                <div v-for="(day, index) in parseContent(row.periodicContent).slice(0, 2)" :key="index">
                  第{{ index + 1 }}天：{{ formatDayContent(day) }}
                </div>
                <div v-if="parseContent(row.periodicContent).length > 2">...</div>
                <div v-if="parseContent(row.periodicContent).length === 0">
                  暂无排班详情
                </div>
              </div>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row.settingId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <div class="total">共 {{ pagination.total }} 条</div>
      <el-select v-model="pagination.size" @change="handleSizeChange" style="width: 100px; margin: 0 10px">
        <el-option label="1条/页" :value="1" />
        <el-option label="3条/页" :value="3" />
        <el-option label="5条/页" :value="5" />
      </el-select>
      <el-pagination v-model:current-page="pagination.current" :total="pagination.total" :page-size="pagination.size"
        layout="prev, pager, next" @current-change="handleCurrentChange" />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" @closed="resetForm">
      <el-form :model="form" label-width="100px" :rules="rules" ref="formRef">
        <el-form-item label="周期名称" prop="settingName">
          <el-input v-model="form.settingName" placeholder="请输入周期名称" />
        </el-form-item>
        <el-form-item label="周期天数" prop="days">
          <el-input-number v-model="form.days" :min="1" :max="30" controls-position="right"
            @change="handleDaysChange" />
        </el-form-item>
        <el-form-item label="排班详情" prop="details">
          <div v-for="day in formDayCount" :key="day" class="day-item">
            <span class="day-label">第{{ day }}天：</span>
            <el-select v-model="form.details[day - 1]" multiple filterable remote reserve-keyword placeholder="请选择班次"
              :remote-method="searchShifts" @focus="loadShifts" @change="(val) => handleShiftChange(val, day - 1)"
              style="width: 100%">
              <el-option v-for="shift in shiftOptions" :key="shift.shiftId"
                :label="`${shift.shiftName} ${shift.startTime}-${shift.endTime}`"
                :value="`${shift.shiftName} ${shift.startTime}-${shift.endTime}`"
                :style="getShiftStyle(day - 1, `${shift.shiftName} ${shift.startTime}-${shift.endTime}`)">
                <span
                  :style="{ color: isShiftOverlapping(day - 1, `${shift.shiftName} ${shift.startTime}-${shift.endTime}`) ? '#f5222d' : 'inherit' }">
                  {{ shift.shiftName }} {{ shift.startTime }}-{{ shift.endTime }}
                  <span v-if="isShiftOverlapping(day - 1, `${shift.shiftName} ${shift.startTime}-${shift.endTime}`)"
                    style="margin-left: 8px; color: #f5222d;">
                    (与已选班次重叠)
                  </span>
                </span>
              </el-option>
            </el-select>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import { useScheSettingStore } from '@/stores/schedule/setting'
import { useShiftStore } from '@/stores/schedule/shift'
import { useRouter } from 'vue-router';
import { useUserStore } from "@/stores/modules/user";

const settingStore = useScheSettingStore()
const shiftStore = useShiftStore()

// 数据状态
const loading = ref(false)
const searchQuery = ref('')
const dialogVisible = ref(false)
const dialogTitle = ref('新增周期排班')
const formRef = ref()
const isEditMode = ref(false)
const currentId = ref<number | null>(null)
const shiftOptions = ref<any[]>([])
const shiftLoading = ref(false)

// 表单数据
const form = ref({
  settingName: '',
  days: 3,
  details: Array(3).fill([]), // 修改为数组形式，用于存储多选班次
  deptId: Number(useUserStore().userInfo.staff.deptId) // 从用户信息获取
})

// 表单验证规则
const rules = {
  settingName: [{ required: true, message: '请输入周期名称', trigger: 'blur' }],
  days: [{ required: true, message: '请设置周期天数', trigger: 'blur' }]
}

// 分页数据
const pagination = ref({
  current: 1,
  size: 3,
  total: 0
})

// 计算属性
const formDayCount = computed(() => {
  return Array.from({ length: form.value.days }, (_, i) => i + 1)
})

const filteredSettings = computed(() => {
  const filtered = settingStore.scheSettings.filter(item =>
    item.settingName.includes(searchQuery.value)
  )

  // 更新总条数
  pagination.value.total = filtered.length

  // 返回当前页数据
  const start = (pagination.value.current - 1) * pagination.value.size
  const end = start + pagination.value.size
  return filtered.slice(start, end)
})

// 方法
//点击去排班按钮后，实现路由跳转
const router = useRouter();
const goToSchedule = () => {
  router.push('/scheduling/schedule');
};

const getCycleDays = (content: any) => {
  try {
    if (typeof content === 'string') {
      const parsed = JSON.parse(content)
      return parsed.cycle_days || parsed.schedule?.length || 0
    }
    return content.cycle_days || content.schedule?.length || 0
  } catch {
    return 0
  }
}

const parseContent = (content: any): any[] => {
  try {
    // 如果已经是对象，直接处理
    if (typeof content === 'object' && content !== null) {
      return content.schedule || []
    }

    // 如果是字符串，尝试解析
    if (typeof content === 'string') {
      const parsed = JSON.parse(content)
      return parsed.schedule || []
    }

    return []
  } catch {
    return []
  }
}

const formatDayContent = (day: any): string => {
  if (!day || !day.slots) return '未设置'

  const slots = Array.isArray(day.slots) ? day.slots : [day.slots]

  return slots.map((slot: any) => {
    // 处理可能已经格式化过的字符串
    if (typeof slot === 'string') return slot
    return `${slot.name || ''} ${slot.time || ''}`
  }).filter(Boolean).join('、')
}

const handleDaysChange = (val: number) => {
  if (val > form.value.details.length) {
    const diff = val - form.value.details.length
    form.value.details = [...form.value.details, ...Array(diff).fill([])]
  } else if (val < form.value.details.length) {
    form.value.details = form.value.details.slice(0, val)
  }
}

const handleAdd = () => {
  dialogTitle.value = '新增周期排班'
  isEditMode.value = false
  dialogVisible.value = true
}

// 加载班次
const loadShifts = async () => {
  try {
    shiftLoading.value = true;
    // 正确调用非分页接口
    await shiftStore.fetchAllActiveShifts();

    // 使用格式化后的班次数据
    shiftOptions.value = shiftStore.formattedShifts.map(shift => ({
      ...shift,
      shiftId: shift.shiftId, // 确保包含唯一标识
      label: `${shift.shiftName} ${shift.startTime}-${shift.endTime}`,
      value: `${shift.shiftName} ${shift.startTime}-${shift.endTime}`
    }));
  } catch (error) {
    ElMessage.error('加载班次失败');
  } finally {
    shiftLoading.value = false;
  }
};

// 搜索班次
const searchShifts = async (query: string) => {
  try {
    shiftLoading.value = true;
    shiftStore.searchQuery = query;
    await shiftStore.fetchAllActiveShifts();

    shiftOptions.value = shiftStore.formattedShifts
      .filter(shift =>
        shift.shiftName.includes(query) ||
        shift.startTime.includes(query) ||
        shift.endTime.includes(query)
      )
      .map(shift => ({
        ...shift,
        label: `${shift.shiftName} ${shift.startTime}-${shift.endTime}`,
        value: `${shift.shiftName} ${shift.startTime}-${shift.endTime}`
      }));
  } catch (error) {
    ElMessage.error('搜索班次失败');
  } finally {
    shiftLoading.value = false;
  }
};

const handleEdit = (row: any) => {
  dialogTitle.value = '编辑周期排班'
  isEditMode.value = true
  currentId.value = row.settingId

  const schedule = parseContent(row.periodicContent)
  const details = schedule.map((day: any) => {
    if (!day.slots) return []

    const slots = Array.isArray(day.slots) ? day.slots : [day.slots]
    return slots.map(slot => {
      // 处理可能已经格式化过的字符串
      if (typeof slot === 'string') {
        // 如果已经是格式化好的字符串，直接返回
        return slot
      }
      // 否则格式化为字符串
      return `${slot.name || ''} ${slot.time || ''}`
    })
  })

  form.value = {
    settingName: row.settingName,
    days: getCycleDays(row.periodicContent),
    details: details,
    deptId: row.deptId
  }

  dialogVisible.value = true
}

const handleDelete = async (settingId: number) => {
  console.log(settingId);
  try {
    await ElMessageBox.confirm('确定要删除这条周期排班吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await settingStore.removeScheSetting(settingId)
    ElMessage.success('删除成功')
    fetchSettings()
  } catch (error) {
    console.log('取消删除')
  }
}

const handleSizeChange = (size: number) => {
  pagination.value.size = size
  pagination.value.current = 1
}

const handleCurrentChange = (current: number) => {
  pagination.value.current = current
}

// 工具函数 - 解析时间字符串为分钟数
const parseTimeToMinutes = (timeStr: string): number => {
  const [hours, minutes] = timeStr.split(':').map(Number)
  return hours * 60 + minutes
}

// 工具函数 - 将分钟数格式化为时间字符串
const formatMinutesToTime = (minutes: number): string => {
  const hours = Math.floor(minutes / 60) % 24
  const mins = minutes % 60
  return `${String(hours).padStart(2, '0')}:${String(mins).padStart(2, '0')}`
}

// 检查两个时间段是否重叠（支持跨日）
const checkTimeOverlap = (timeRange1: string, timeRange2: string): boolean => {
  // 解析时间段，格式为"08:00-17:00"或"23:00-07:00"(跨日)
  const parseTimeRange = (range: string) => {
    const [start, end] = range.split('-')
    const startMin = parseTimeToMinutes(start)
    let endMin = parseTimeToMinutes(end)

    // 处理跨日情况
    if (endMin <= startMin) {
      endMin += 24 * 60 // 第二天的时间
    }

    return { start: startMin, end: endMin }
  }

  const t1 = parseTimeRange(timeRange1)
  const t2 = parseTimeRange(timeRange2)

  // 边界情况：恰好相邻的时间段不算重叠
  return !(t1.end <= t2.start || t2.end <= t1.start)
}

// 获取班次的时间部分
const getShiftTime = (shiftStr: string): string => {
  return shiftStr.split(' ')[1] || ''
}

// 计算当前天已选班次的时间段
const getSelectedTimes = (dayIndex: number): string[] => {
  return (form.value.details[dayIndex] || []).map(shift => getShiftTime(shift))
}

// 检查班次是否与已选班次重叠
const isShiftOverlapping = (dayIndex: number, shift: string): boolean => {
  const selectedTimes = getSelectedTimes(dayIndex)
  const newShiftTime = getShiftTime(shift)

  if (!newShiftTime) return false

  return selectedTimes.some(time => checkTimeOverlap(time, newShiftTime))
}

// 获取班次的显示样式（用于高亮）
const getShiftStyle = (dayIndex: number, shift: string) => {
  return {
    backgroundColor: isShiftOverlapping(dayIndex, shift) ? '#fff2f0' : '',
    color: isShiftOverlapping(dayIndex, shift) ? '#f5222d' : 'inherit'
  }
}

// 班次选择逻辑
// 班次变更处理
const handleShiftChange = (value: string[], dayIndex: number) => {
  // 获取新增的班次（如果有）
  const currentShifts = form.value.details[dayIndex] || []
  const newShifts = value.filter(item => !currentShifts.includes(item))

  // 检查所有新增班次是否重叠
  for (const newShift of newShifts) {
    if (isShiftOverlapping(dayIndex, newShift)) {
      ElMessage.warning(`班次 ${newShift} 与已选班次时间段重叠，请重新选择`)
      // 恢复之前的选择
      form.value.details[dayIndex] = [...currentShifts]
      return
    }
  }

  // 检查移除班次后剩余班次之间是否有重叠
  const removedShifts = currentShifts.filter(item => !value.includes(item))
  if (removedShifts.length > 0) {
    const remainingShifts = value
    const timeRanges = remainingShifts.map(getShiftTime)

    // 检查所有剩余班次两两之间是否有重叠
    for (let i = 0; i < timeRanges.length; i++) {
      for (let j = i + 1; j < timeRanges.length; j++) {
        if (checkTimeOverlap(timeRanges[i], timeRanges[j])) {
          ElMessage.warning('移除班次后，剩余班次之间存在时间段重叠')
          // 恢复之前的选择
          form.value.details[dayIndex] = [...currentShifts]
          return
        }
      }
    }
  }

  // 没有重叠，更新选择
  form.value.details[dayIndex] = value
}

// // 检查当前选择的班次是否与已选班次重叠
// const checkShiftOverlap = (dayIndex: number, newShift: string): boolean => {
//   const currentShifts = form.value.details[dayIndex]
//   if (!currentShifts || currentShifts.length === 0) return false

//   // 从班次字符串中提取时间部分
//   const newShiftTime = newShift.split(' ')[1] // 格式为"班次名 08:00-17:00"

//   for (const shift of currentShifts) {
//     const existingShiftTime = shift.split(' ')[1]
//     if (checkTimeOverlap(newShiftTime, existingShiftTime)) {
//       return true
//     }
//   }

//   return false
// }

const submitForm = async () => {
  try {
    await formRef.value.validate()

    // 转换表单数据为新的数据结构
    const schedule = form.value.details.map((detail, index) => {
      // detail现在是一个数组，包含选中的班次字符串
      const slots = detail.map(item => {
        // 解析班次字符串，格式为"班次名称 开始时间-结束时间"
        const [name, time] = item.trim().split(' ')

        // 在shiftOptions中查找匹配的班次，获取shiftId
        const matchedShift = shiftOptions.value.find(
          shift => `${shift.shiftName} ${shift.startTime}-${shift.endTime}` === item
        )

        return {
          name: name || '',
          time: time || '',
          shiftId: matchedShift ? matchedShift.shiftId : null // 添加shiftId
        }
      })

      return {
        day: index + 1,
        // 如果只有一个时段，直接存储为对象；多个时段存储为数组
        slots: slots.length === 1 ? slots[0] : slots
      }
    })

    const formData = {
      settingName: form.value.settingName,
      periodicContent: JSON.stringify({
        schedule: schedule,
        cycle_days: form.value.days
      }),
      deptId: form.value.deptId
    }

    if (isEditMode.value && currentId.value) {
      await settingStore.editScheSetting({
        settingId: currentId.value,
        ...formData
      })
      ElMessage.success('更新成功')
    } else {
      await settingStore.addScheSetting(formData)
      ElMessage.success('添加成功')
    }

    dialogVisible.value = false
    fetchSettings()
  } catch (error) {
    console.error('表单提交失败:', error)
    ElMessage.error('提交失败，请检查数据格式')
  }
}

const resetForm = () => {
  formRef.value?.resetFields()
  form.value = {
    settingName: '',
    days: 3,
    details: Array(3).fill([]), // 重置为数组形式
    deptId: Number(useUserStore().userInfo.staff.deptId)
  }
  currentId.value = null
  isEditMode.value = false
}

// 生命周期钩子
onMounted(() => {
  fetchSettings()
  loadShifts()
})

const fetchSettings = async () => {
  try {
    loading.value = true
    await settingStore.getScheSettings()
  } catch (error) {
    ElMessage.error('获取排班设置失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.cycle-scheduling {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  .title-and-button {
      display: flex;
      align-items: center;
      gap: 10px; /* 控制标题和按钮的间距，可根据需求调整 */
    }

    .header-actions {
      display: flex;
      align-items: center;
    }
}

.header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
  color: #333;
}

/* .header-actions {
  display: flex;
  align-items: center;
} */

.pagination {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.total {
  margin-right: 10px;
  color: #606266;
}

.day-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.day-label {
  width: 60px;
  flex-shrink: 0;
  color: #606266;
}

.cycle-content {
  position: relative;
}

.content-text {
  min-height: 60px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.content-text div {
  margin-bottom: 4px;
}

.content-text div:last-child {
  margin-bottom: 0;
}
</style>

<style>
.cycle-tooltip {
  max-width: 300px;
  padding: 12px;
  line-height: 1.5;
}

.cycle-tooltip .tooltip-content div {
  margin-bottom: 4px;
}

.el-table__body tr {
  height: 60px;
}

.el-table__body td {
  padding: 16px 0;
}

.day-item {
  margin-bottom: 16px;
}

.day-item:last-child {
  margin-bottom: 0;
}

.day-label {
  display: inline-block;
  width: 60px;
  margin-right: 8px;
  text-align: right;
  color: #606266;
}

.el-select-dropdown__item {
  transition: all 0.3s;
}

.el-select-dropdown__item.highlight-overlap {
  background-color: #fff2f0;
  color: #f5222d;
}

.overlap-warning {
  margin-left: 8px;
  color: #f5222d;
  font-size: 12px;
}
</style>